<template>
    <div class="labeltype-panel-wrapper">
        <div class="label-type-1">
            <div class="label-title">机器列表</div>
            <Plus class="label-icon-title" style="margin-right: 3px" @click="handleNewRemote()" />
            <DArrowLeft class="label-icon-title" @click="emit('toggleRemoteList')" />
        </div>
        <div class="label-type-2" @mouseenter="onMouseEnter($event, 'local')" @mouseleave="onMouseLeave($event, 'local')">
            <Platform class="label-icon green" />
            <div>Localhost</div>
            <div v-if="showButtonID === 'local'" class="label-icon-dynamic-wrapper" style="right: 27px">
                <Right class="label-icon-dynamic" @click="onClickEnter('local')"></Right>
            </div>
        </div>
        <div v-for="(row, index) in _remote_list" :key="row.id" class="label-type-2" @mouseenter="onMouseEnter($event, row.id)" @mouseleave="onMouseLeave($event, row.id)">
            <Platform class="label-icon" :class="row.color" />
            Remote:{{ row.name }}
            <div v-if="showButtonID === row.id" class="label-icon-dynamic-wrapper">
                <SwitchButton v-if="row.color !== 'green'" class="label-icon-dynamic" @click="onClickConnect(row.id)"> </SwitchButton>
                <Right v-if="row.color === 'green'" class="label-icon-dynamic" @click="onClickEnter(row.id)"></Right>
                <el-dropdown trigger="click">
                    <More class="label-icon-dynamic"></More>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item v-if="row.color === 'green'" :icon="TurnOff" @click="handleDisconnect(row)"> 关闭 </el-dropdown-item>
                            <el-dropdown-item :icon="Setting" @click="handleSetting(row)"> 配置 </el-dropdown-item>
                            <el-dropdown-item :icon="Delete" @click="handleDelete(row)"> 删除 </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </div>
    </div>
    <!-- create remote dialog -->
    <el-dialog v-model="dialogFormVisible" title="添加远程" align-center width="450px" :before-close="handleBeforeClose">
        <el-form ref="editForm" :model="form" :rules="rules">
            <el-form-item label="标签" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="主机" :label-width="formLabelWidth" prop="host">
                <el-input v-model="form.host" />
            </el-form-item>
            <el-form-item label="端口" :label-width="formLabelWidth" prop="port">
                <el-input v-model="form.port" />
            </el-form-item>
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="认证方式" :label-width="formLabelWidth">
                <el-radio-group v-model="form.validation">
                    <el-radio :label="`Password`"></el-radio>
                    <el-radio :label="`IdentityFile`"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.validation === 'Password'" label="密码" :label-width="formLabelWidth" prop="password">
                <el-input v-model="form.password" type="password" />
            </el-form-item>
            <el-form-item v-if="form.validation === 'IdentityFile'" label="私钥文件" :label-width="formLabelWidth" prop="identity_file">
                <el-input v-model="form.identity_file" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="onAddRemote"> 确定 </el-button>
                <el-button @click="showDialog(false)">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import API from '@/js/api';
import { onMounted, onUnmounted, ref, reactive, inject, getCurrentInstance } from 'vue';
import { Setting, Delete, TurnOff } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance();
let vueApp = inject('vueApp');

const emit = defineEmits(['toggleRemoteList', 'reload']);
const showButtonID = ref('');
const _remote_list = ref([]);

// 对话框相关的变量
let dialogFormVisible = ref(false);
let formLabelWidth = '80px';
let form = reactive({
    id: null,
    name: '',
    host: '',
    port: 22,
    username: '',
    validation: 'Password',
    password: '',
    identity_file: ''
});
let rules = reactive({
    name: [
        {
            required: true,
            message: '请输入标签',
            trigger: 'blur'
        }
    ],
    host: [
        {
            required: true,
            message: '请输入主机地址',
            trigger: 'blur'
        }
    ],
    port: [
        {
            required: true,
            message: '请输入端口',
            trigger: 'blur'
        }
    ],
    username: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }
    ],
    identity_file: [
        {
            required: true,
            message: '请输入私钥文件',
            trigger: 'blur'
        }
    ]
});

function onMouseEnter(event, buttonID) {
    // console.log(event.target);
    showButtonID.value = buttonID;
}

function onMouseLeave(event, buttonID) {
    // console.log(event.target);
    // showButtonID.value = null;
}

function showDialog(show) {
    dialogFormVisible.value = show;
    vueApp.monitorKeyEvent(!show);
}

function handleBeforeClose(done) {
    vueApp.monitorKeyEvent(true);
    done();
}

async function getRemoteList() {
    let result = await API.local.invoke('GetRemoteList');
    if (result.code == 0) {
        let remotes = result.msg.map((item) => {
            if (item.ssh_status == 1) {
                item.color = 'green';
            } else {
                item.color = '';
            }
            return item;
        });
        // console.log(remotes);
        _remote_list.value = remotes;
    }
}

async function onClickEnter(remoteId) {
    // console.log(`onClickEnter remoteId = ${remoteId}`);
    // 判断远程服务器是否连同
    if (remoteId != 'local') {
        let result = await API.local.invoke('RemoteTest', { remoteId: remoteId });
        if (result.code == 0) {
            await API.setProvider(`remote:${remoteId}`);
            emit('reload', true);
        } else {
            await getRemoteList();
            ElMessage.error(`远程服务器${remoteId}连接失败！`);
        }
    } else {
        await API.setProvider('local');
        emit('reload', true);
    }
}

async function onClickConnect(remoteId) {
    // console.log(`onClickConnect remoteId = ${remoteId}`);
    try {
        let result = await API.local.invoke('RemoteConnect', { remoteId: remoteId });
        if (result.code == 0) {
            await getRemoteList();
            await API.setProvider(`remote:${remoteId}`);
            emit('reload', true);
        } else {
            ElMessage.error('连接远程服务器失败，错误信息:' + result.msg);
        }
    } catch (error) {
        ElMessage.error('连接远程服务器失败，错误信息:' + error);
    }
}

async function handleDisconnect(row) {
    // console.log(`handleDisconnect row = `, row);
    let result = await API.local.invoke('RemoteDisconnect', { remoteId: row.id });
    console.log(result);
    if (result.code == 0) {
        await getRemoteList();
        await API.setProvider('local');
        emit('reload', false);
    } else {
        ElMessage.error('断开远程服务器失败，错误信息:' + result.msg);
    }
}

function showDialog(show) {
    dialogFormVisible.value = show;
    vueApp.monitorKeyEvent(!show);
}

function handleBeforeClose(done) {
    vueApp.monitorKeyEvent(true);
    done();
}

async function handleNewRemote() {
    form.id = null;
    showDialog(true);
}

async function handleSetting(row) {
    console.log(`handleSetting row = `, row);
    let result = await API.local.invoke('GetRemoteInfo', { remoteId: row.id });
    if (result.code == 0) {
        let config = result.msg;
        form.id = config.id;
        form.name = config.name;
        form.host = config.host;
        form.port = config.port;
        form.username = config.username;
        form.password = config.password;
        form.identity_file = config.identity_file;
        showDialog(true);
    } else {
        ElMessage.error('获取远程配置失败，错误信息:' + result.msg);
    }
}

async function handleDelete(row) {
    console.log(`handleDelete row = `, row);
    let result = await API.local.invoke('DeleteRemote', { remoteId: row.id });
    if (result.code == 0) {
        ElMessage.success('删除远程配置成功！');
        getRemoteList();
    } else {
        ElMessage.error('删除远程配置失败，错误信息:' + result.msg);
    }
}

async function onAddRemote() {
    let editForm = proxy.$refs.editForm;
    await editForm.validate(async (valid, fields) => {
        if (valid) {
            let result = null;
            let api_method = '';
            let tip_msg = '';

            // 根据form.id和form.validation信息，确定请求API的参数
            if (!form.id) {
                api_method = 'AddRemote';
                tip_msg = '创建';
            } else {
                api_method = 'UpdateRemote';
                tip_msg = '更新';
            }

            if (form.validation == 'Password') {
                form.identity_file = '';
            } else {
                form.password = '';
            }

            // 调用本地接口
            result = await API.local.invoke(api_method, {
                id: form.id,
                name: form.name,
                host: form.host,
                port: form.port,
                username: form.username,
                password: form.password,
                identity_file: form.identity_file
            });

            // 弹出提示信息
            if (result.code == 0) {
                ElMessage.success(tip_msg + '远程配置成功！');
            } else {
                ElMessage.error(tip_msg + '远程配置失败，错误原因：' + result.msg);
            }

            // 更新列表
            getRemoteList();
            showDialog(false);
        } else {
            console.log('error submit!', fields);
        }
    });
}

onMounted(() => {
    getRemoteList();
});

onUnmounted(() => {});
</script>

<style scoped>
.labeltype-panel-wrapper {
    display: block;
    background-color: rgb(209, 213, 218);
    width: 100%;
    height: calc(100% - 0px);
}

.label-type-1 {
    display: flex;
    font-size: 14px;
    font-weight: 700;
    line-height: 20px;
    padding: 10px 5px 10px 10px;
    color: rgb(237, 239, 241);
    background-color: rgb(69, 65, 65);
    cursor: default;
}

.label-type-2 {
    position: relative;
    background-color: rgb(255, 255, 255);
    margin: 2px;
    padding: 10px 25px 10px 10px;
    line-height: 16px;
    font-size: 12px;
    color: rgb(66, 66, 67);
    display: flex;
}

.label-type-2:hover {
    background-color: rgb(255, 255, 255);
    cursor: default;
}

.label-type-2.selected {
    background-color: rgb(222, 222, 222);
    cursor: default;
    font-weight: 700;
}

.label-title {
    padding-right: 80px;
}

.label-icon {
    padding: 2px 5px 0px 0px;
    width: 1.2em;
    height: 1.2em;
    color: rgb(66, 66, 67);
}

.label-icon.green {
    color: rgb(35, 213, 8);
}

.label-icon.red {
    color: rgb(236, 92, 70);
}

.label-icon-title {
    width: 16px;
    height: 16px;
    color: rgb(244, 244, 244);
    padding: 2px;
}

.label-icon-dynamic {
    width: 16px;
    height: 16px;
    color: rgb(66, 66, 67);
    font-weight: 800;
    padding: 0px 3px 0px 3px;
    outline: none;
    cursor: pointer;
}

.label-icon-title:hover {
    background-color: rgb(102, 102, 104);
}

.label-icon-dynamic-wrapper {
    display: block;
    position: absolute;
    right: 5px;
}
</style>
